<template>
  <div class="app">
    <el-row :gutter="5" class="content">
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="title">试题列表</div>
          <div v-for="(subject, index) in subjects" :key="subject.subjectId">
            <h3>{{ index + 1 }}. {{ subject.subjectTitle }}</h3>
            <div v-if="subject.subjectType === 2">
              <el-checkbox-group v-model="subject.answers">
                <el-checkbox
                  v-for="option in subject.options"
                  :key="option.optionId"
                  :label="option.optionTitle"
                  style="display: flex"
                >
                  {{ option.optionTitle }}. {{ option.optionContent }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div v-else-if="subject.subjectType === 6">
              <el-input v-model="subject.answer" style="width: 80%"></el-input>
            </div>
            <div v-else>
              <el-radio-group v-model="subject.answer">
                <el-radio
                  v-for="option in subject.options"
                  :key="option.optionId"
                  :label="option.optionTitle"
                  style="display: flex"
                >
                  {{ option.optionTitle }}. {{ option.optionContent }}
                </el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="title">考试详情</div>
          <div>
            <div class="detail">{{ subjectTitle }}</div>
            <div class="detail" v-if="paperName != null">{{ paperName }}</div>
            <div>
              <el-button-group>
                <el-button size="small" type="primary" v-if="showSubmitBtn" @click="submitExam"
                  >提交试卷</el-button
                >
                <el-button size="small" type="danger" @click="back">返回上级</el-button>
              </el-button-group>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { BizSubjectController, BizExamController, DictionaryController } from '@/api';
export default {
  name: 'ExamView',
  data() {
    return {
      sceneType: null,
      moduleType: null,
      personnelType: null,
      examType: null,
      examLevel: 0,
      subjects: [],
      sceneTypeList: [],
      paperId: null,
      paperName: null,
      subjectTitle: '',
      showSubmitBtn: true,
      record: {
        sceneType: '',
        moduleType: '',
        examType: '',
        records: []
      }
    };
  },
  methods: {
    back() {
      if (this.moduleType === 2) {
        this.$router.replace({
          name: 'frontScene',
          query: { sceneType: this.sceneType, personnelType: this.personnelType }
        });
      } else if (this.moduleType === 3) {
        this.$router.replace({
          name: 'course',
          query: { sceneType: this.sceneType, personnelType: this.personnelType }
        });
      }
    },
    submitExam() {
      let subRecs = {};
      subRecs = this.subjects.map(item => ({
        subjectId: item.subjectId,
        subjectTitle: item.subjectTitle,
        subjectType: item.subjectType,
        answer: item.answer,
        answers: item.answers
      }));
      this.record.sceneType = this.sceneType;
      this.record.moduleType = this.moduleType;
      this.record.personnelType = this.personnelType;
      this.record.examMode = this.examType;
      this.record.paperId = this.paperId;
      this.record.examLevel = this.examLevel;
      this.record.records = subRecs;
      this.recordExam();
    },
    getSubjects() {
      let params = {};
      params.subjectFilter = {
        personnelType: this.personnelType,
        moduleType: this.moduleType,
        materialType: this.materialType,
        sceneType: this.sceneType,
        examMode: this.examType,
        subjectLevel: this.examLevel
      };
      return new Promise((resolve, reject) => {
        BizSubjectController.findByFront(this, params)
          .then(res => {
            this.paperId = res.data.paperId;
            this.paperName = res.data.paperName;
            const subjectsData = res.data.subjects;
            this.subjects = subjectsData.map(subject => {
              return {
                ...subject,
                answer: '', // 添加 answer 字段
                answers: [] // 添加 answers 字段
              };
            });
            if (this.subjects && this.subjects.length === 0) {
              this.showSubmitBtn = false;
            }
          })
          .catch(e => {
            this.showSubmitBtn = false;
            reject(e);
          });
      });
    },
    loadSceneTypeList() {
      let params = {
        dictCode: 'SceneType'
      };
      return new Promise((resolve, reject) => {
        DictionaryController.dictGlobalDict(this, params)
          .then(res => {
            resolve(res.getList());
          })
          .catch(e => {
            reject(e);
          });
      });
    },
    recordExam() {
      let shouldSubmit = true;
      if (this.record && this.record.records) {
        this.record.records.forEach(k => {
          // 检查answer和answers是否同时为空
          if (!k.answer && k.answers.length === 0) {
            shouldSubmit = false;
            // 终止循环
          }
        });

        if (!shouldSubmit) {
          this.$message.warning('请全部作答完成后提交');
          return false;
        }
      }
      BizExamController.record(this, this.record)
        .then(res => {
          if (res) {
            if (this.moduleType === 2) {
              if (res.data.passAble) {
                this.$message.success('恭喜你！闯关成功!');
                this.$router.replace({
                  name: 'examDetail',
                  query: {
                    sceneType: this.sceneType,
                    moduleType: this.moduleType,
                    personnelType: this.personnelType,
                    examType: this.examType,
                    examLevel: this.examLevel
                  }
                });
              } else {
                this.$message.error('闯关失败！请再接再励!');
                this.back();
              }
            } else if (this.moduleType === 3) {
              this.$router.replace({
                name: 'examDetail',
                query: {
                  sceneType: this.sceneType,
                  moduleType: this.moduleType,
                  personnelType: this.personnelType,
                  examType: this.examType
                }
              });
            }
          }
        })
        .catch(e => {
          console.error(e);
        });
    }
  },
  mounted() {
    const sceneType = this.$route.query.sceneType;
    this.sceneType = sceneType;
    const moduleType = this.$route.query.moduleType;
    this.moduleType = moduleType;
    const personnelType = this.$route.query.personnelType;
    this.personnelType = personnelType;
    const examType = this.$route.query.examType;
    this.examType = examType;
    const examLevel = this.$route.query.examLevel;
    this.examLevel = examLevel;
    this.loadSceneTypeList().then(res => {
      this.sceneTypeList = res;
      if (this.moduleType === 2) {
        this.subjectTitle = this.sceneTypeList.find(s => parseInt(s.id) === this.sceneType)?.name;
      }
    });
    this.getSubjects();
  }
};
</script>

<style scoped>
.app {
  height: 100vh;
  padding: 35px;
}

.app .content {
  width: 100%;
  height: 95vh;
}

.app .content .box-card {
  width: 100%;
  height: 95vh;
  overflow-y: auto;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.title {
  height: 30px;
  font-size: 16px;
  line-height: 30px;
}

.detail {
  height: 30px;
  font-size: 16px;
  font-style: italic;
  font-weight: bolder;
}
/deep/ .el-radio__label {
  white-space: normal; /* 换行 */
}

/deep/ .el-checkbox__label {
  white-space: normal; /* 换行 */
}
</style>
